package com.yhsimon.syn;

//模拟死锁
public class DeadLock {
    public static void main(String[] args) {
        Makeup g1 = new Makeup(0, "小花");
        Makeup g2 = new Makeup(1, "小红");
        g1.start();
        g2.start();
    }
}

//口红 资源1
class Lipstick {

}

//镜子 资源2
class Mirror {

}

class Makeup extends Thread {

    //需要的资源只有一份，用static来保证一份
    static Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();

    int choice; //选择
    String name; //角色姓名

    public Makeup(int choice, String name) {
        this.choice = choice;
        this.name = name;
    }

    @Override
    public void run() {
        try {
            makeup();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void makeup() throws InterruptedException {
        if (choice == 0) {
            synchronized (mirror) {//获得镜子的锁
                System.out.println(this.name + "获得了镜子");
                Thread.sleep(1000);
//                synchronized (lipstick) {
//                    System.out.println(this.name + "获得了口红"); //发生死锁
//                }
            }
            synchronized (lipstick) {//一秒钟后想获得口红，且此时mirror锁已经释放
                System.out.println(this.name + "获得了口红");
            }
        } else {
            synchronized (lipstick) {//获得口红的锁
                System.out.println(this.name + "获得了口红");
                Thread.sleep(2000);
//                synchronized (mirror) {
//                    System.out.println(this.name + "获得了镜子"); //发生死锁
//                }
            }
            synchronized (mirror) {//两秒后想获得镜子，此时口红锁已经释放
                System.out.println(this.name + "获得了镜子");
            }
        }
    }
}